/**
* @describe 
* @author 游金宇(KM)
* @date 2024-09-12 11:35:02
*/

import { error, log } from "cc";

import { cat, ToastType } from "@shimotsuki/core";
import { PitayaError } from "sgc";
import { QueryAliveRoom } from "../query-alive-room";

type JoinBattleOptions =
    ({ isAudience: boolean, isReload: boolean })

/**加入战局 */
export default async function JoinBattle(options: JoinBattleOptions) {
    const { isAudience, isReload } = options

    let title: string;
    if (isAudience) {
        title = isReload ? '加入观战中' : '等待游戏开局...';
    } else {
        title = isReload ? '加入战局中' : '等待其他玩家加入...';
    }

    cat.gui.showLoading({ title });

    try {
        await cat.util.commontils.retryRequest(async () => {
            if (isAudience) {
                await cat.game_ws.Watch()
                log('加入观战')
            } else {
                await cat.game_ws.JoinBattle()
                log('加入战局')
            }
        })
    } catch (err) {
        cat.game_ws.destroy()
        const { msg, code } = err as PitayaError
        cat.gui.showToast({ title: `${code}：${msg}`, type: ToastType.FIXED, fixed_time: 2.0 })
        if (isAudience) {
            error('加入观战错误:', code, msg)
        } else {
            error('加入战局错误:', code, msg)
        }

        await QueryAliveRoom()

        // 回到首页
        cat.gui.loadScene(cat.store.room.roomInfo.id ? 'room' : 'lobby')

    }
}

